<route lang="json">
{
  "style": {
    "navigationBarTitleText": "订单退货",
    "backgroundColorContent": "#f1f1f1"
  }
}
</route>

<template>
  <!-- 弹出框结构 -->
  <div class="li-popup">
    <div class="popup-mask" :class="popupMask ? 'popup-mask-show' : ''" @click="hide_popup">
    </div>
    <div class="popup-container" :class="popupContainer ? 'popup-container-show' : ''">
      <div class="popup-content">
        <div class="popup-body">
          <nut-form ref="ruleForm" :model-value="form">

            <nut-form-item label="日期">
              <date-picker :min="minDate" :max="maxDate" v-model="form.sysDate_line" title="交易日期" />
            </nut-form-item>
            <nut-form-item label="系统流水号">
              <nut-input v-model="form.order" placeholder="请输入流水号" type="text" />
            </nut-form-item>
 
          </nut-form>
          <div class="li-searchBar-btn">
            <div class="li-cz shake_o" @click="resetForm">重置</div>
            <div class="li-ss shake_o" @click="searchList">搜索</div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="refund">

    <div class="li-searchBar">
      <div class="li-rantangle">
        <div class="li-btnleft li-butStyle" :class="searchKey !== '全部' ? 'li-lftactive' : ''" >
          <div class="li-texts">{{ searchKey }}</div>
        </div>
        <div class="li-btnright li-butStyle" :class="searchKey !== '全部' ? 'li-ritactive' : ''" @click="show_popup">筛选
        </div>
      </div>
    </div>
    <div style="width: 100%;height: 120rpx;"></div>

    <!-- <div class="input">
      <nut-form>
        <nut-form-item label="流水序号">
          <nut-input v-model="order" placeholder="请输入订单号" type="text" />
        </nut-form-item>
        <nut-cell>
          <nut-button type="primary" size="small" @click="query">查询</nut-button>
        </nut-cell>
      </nut-form>
    </div> -->
    <div class="list">
      <nut-empty v-if="list.length === 0" description="暂无数据"></nut-empty>
      <scroll-view v-else scroll-y :style="{ height: windowHeight - customBarHeight - 40 + 'px' }"
        @scrolltolower="scrolltolower">

        <div class="li-card-item shake_o shadow" v-for="(item, index) in list" :key="index" @click="goRefund(item)">
          <div class="content-box1 b-c1">
            <div class="cb-lft">
              <div class="first">{{ item.fristName }}</div>
              <div class="info">
                <div class="name">{{ item.mchtNo }}</div>
                <div class="id">{{ masktring(item.sysSeqNum) }}</div>
              </div>
            </div>
            <div class="cb-rit c1">{{ rfdName(item.rfdFlag) }}</div>
          </div>
          <div class="content-box2">
            <div class="item" v-if="item.terminalNo">
              <div class="lable">终端编号</div>
              <div class="name">{{ item.terminalNo }}</div>
            </div>
            <div class="item">
              <div class="lable">交易金额</div>
              <div class="name"><nut-price :price="item.transAmt" symbol="¥" custom-style="color: #000" /></div>
            </div>
            <div class="item">
              <div class="lable">已退货金额</div>
              <div class="name"><nut-price :price="item.refundedAmount" symbol="¥" custom-style="color: #000" /></div>
            </div>
            <div class="item" v-if="item.authIdr">
              <div class="lable">授权码</div>
              <div class="name">{{ item.authIdr }}</div>
            </div>
          </div>
          <div class="content-bot">
            <div class="cbt-lft">交易日期:{{ item.transDate }}</div>
            <div class="cbt-rit">查看<i class="i-ri:arrow-right-s-line"></i></div>
          </div>
          <div style="padding-bottom: 10rpx;"></div>
        </div>
        <div class="end" v-if="end">没有更多数据了</div>
        <div class="loading" v-if="loading">
          <nut-icon name="loading"></nut-icon>
          数据加载中...
        </div>
      </scroll-view>
    </div>

  </div>
</template>

<script lang="ts" setup>
import mcht from '@/api/mcht'
import { useAppStore, useHomeStore } from '@/store'
import { throttle } from '@/utils/shared.ts'
import dayjs from 'dayjs'

const now = dayjs()
const minDate = now.subtract(6, 'month').toDate()
const maxDate = now.toDate()
const {
  windowHeight,
  customBarHeight
} = storeToRefs(useAppStore())

const {
  modifyRefund
} = storeToRefs(useHomeStore())

const order = ref('')

const list = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(5)
const end = ref<boolean>(false)
const loading = ref<boolean>(false)
 
async function getList (p: number) {
  loading.value = true
  isLoading.value = false
  const { data } = await mcht.getRefundTransactions({
    pageNum: p,
    pageSize: pageSize.value,
    sysSeqNum: form.order,
    sysDate: dayjs(form.sysDate_line).format('YYYYMMDD')
  })
  loading.value = false
  isLoading.value = true
  if (data.status === 'success') {
    total.value = data.data.total
    page.value = data.data.pageNum

    let lists = data?.data.list
    if (lists) {
      lists.forEach((e) => {
        e.fristName = '退'
      })
    }

    if (p === 1) {
      list.value = lists
    } else {
      list.value = list.value.concat(lists)
    }
    if (page.value * pageSize.value >= total.value) {
      end.value = true
    } else {
      end.value = false
    }
  }
}

// async function query () {
//   if (order.value) {
//     getList(1)
//   } else {
//     uni.showToast({
//       icon: 'none',
//       title: '请输入订单号',
//     })
//   }
// }

const throttledGetList = throttle(getList, 600)
async function query() {
  list.value = []
  // getList(1)
  throttledGetList(1)
}

const isLoading = ref<boolean>(true)
function scrolltolower() {
  if (!end.value) {
    if (isLoading.value) {
      getList(page.value + 1)
    }
  }
}

function goRefund (item: any) {
  modifyRefund.value = item
  uni.navigateTo({
    url: `/pages/home/refund/refund?sysSeqNum=${item.sysSeqNum}`
  })
}

function rfdName(rfd: string) {
  return {
    '0': '正常',
    '1': '已退货',
  }[rfd]
}

function masktring(str) {
  if (str.length <= 16) {
    return str
  }
  let start = str.slice(0, 6)
  let end = str.slice(-6)
  return start + ' **** ' + end
}

// 弹框修改

const form = reactive({
  sysDate_line: dayjs().format('YYYY-MM-DD'),
  order: '',
})

const popupMask = ref<boolean>(false)
const popupContainer = ref<boolean>(false)
const searchKey = ref<string>('全部')

function show_popup() {
  popupMask.value = true
  popupContainer.value = true
}

function hide_popup() {
  popupMask.value = false
  popupContainer.value = false
}

function searchList() {
  if (!form.order) {
    uni.showToast({
      icon: 'none',
      title: '请输入订单号',
    })
    return
  }

  let result = [form.sysDate_line, form.order]
    .filter(item => item)
    .join('/');
  if (!result) {
    result = '全部'
  }
  searchKey.value = result
  resetList()
  query()
  hide_popup()
}
function clearSearchList() {
  resetForm()
  searchKey.value = '全部'
  resetList()
  query()
}

function resetForm() {
  form.sysDate_line = dayjs().format('YYYY-MM-DD HH:mm')
  // form.endDate_line = dayjs().format('YYYY-MM-DD HH:mm')
  form.order = ''
}

function resetList() {
  list.value = []
  total.value = 0
  page.value = 1
  end.value = false
}

function convertDateFormat(dateString) {
  // 检查输入的格式是否正确
  // const datePattern = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;
  // if (!datePattern.test(dateString)) {
  //   throw new Error("输入格式不正确，应为 'YYYY-MM-DD HH:mm:ss'");
  // }
  const datePattern = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/;
  if (!datePattern.test(dateString)) {
    throw new Error("输入格式不正确，应为 'YYYY-MM-DD HH:mm'");
  }

  // 替换，并去除连接符和空格
  return dateString.replace(/[- :]/g, '');
}

</script>

<style lang="sass" scoped>
.refund
  .list
    padding: 20rpx
    .item
      background-color: #fff
      border-radius: 6px
      margin-bottom: 15px
      .top
        display: flex
        justify-content: space-between
        padding: 0 10px
        font-weight: bold
    .end
      text-align: center
      color: #8e8e8e
    .loading
      text-align: center
      color: #8e8e8e

/* 筛选按钮相关 end */
:deep(.nut-cell-group__wrap)
  box-shadow: none!important
  margin: 0!important
  padding: 10rpx 0!important

:deep(.nut-cell-group .nut-cell::after)
  border-bottom: none
</style>